package pt.fct.mpc.lastfm.artist;

import java.util.List;
import java.util.Vector;

import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;



public class AlbumsXmlHandler extends DefaultHandler{

	private List<AlbumData> albuns = new Vector<AlbumData>();
	private AlbumData albumDataSet = null;
	private String position = "";
	private String artist = "";

	public List<AlbumData> getParsedData() {
		return this.albuns;
	}

	public void startDocument() throws SAXException {
		this.albuns = new Vector<AlbumData>();
	}

	public void endDocument() throws SAXException {
		// Nothing to do
	}

	/** Gets be called on opening tags like:
	 * <tag>
	 * Can provide attribute(s), when xml was like:
	 * <tag attribute="attributeValue">*/
	public void startElement(String namespaceURI, String localName,
			String qName, Attributes atts) throws SAXException {
		position = position.concat("." + localName);
		if (localName.equals("album")) {
			albumDataSet = new AlbumData();
			albumDataSet.setArtistName(artist);
		}
		if (localName.equals("image")) {
			position = position.concat("." + atts.getValue("size")); 
		}
		if (localName.equals("topalbums")) {
			artist = atts.getValue("artist"); 
		}
	}

	/** Gets be called on closing tags like:
	 * </tag> */
	public void endElement(String namespaceURI, String localName, String qName)
	throws SAXException {
		if (localName.equals("album")) {
			albuns.add(albumDataSet);
		}
		position = position.substring(0, position.lastIndexOf("." + localName));
	}

	/** Gets be called on the following structure:
	 * <tag>characters</tag> */
	public void characters(char ch[], int start, int length) {
		if(position.compareTo(".lfm.topalbums.album.name")==0){
			albumDataSet.setAlbumName(new String(ch, start, length));
		} else if(position.compareTo(".lfm.topalbums.album.mbid")==0){
			albumDataSet.setMbid(new String(ch, start, length));
		} else if(position.compareTo(".lfm.artist.image.small")==0){
			albumDataSet.setImage_small(new String(ch, start, length));
		} else if(position.compareTo(".lfm.artist.image.medium")==0){
			albumDataSet.setImage_medium(new String(ch, start, length));
		} else if(position.compareTo(".lfm.artist.image.large")==0){
			albumDataSet.setImage_large(new String(ch, start, length));
		} else if(position.compareTo(".lfm.artist.image.extralarge")==0){
			albumDataSet.setImage_extralarge(new String(ch, start, length));
		} 
	}
}